<template>
  <CrudTable
    :buttons="tableButtons"
    row-selection-type="multiple"
    :columns="tableColumns"
    @currentChange="handleSelectChange"
    :tableData="pageData.tableData.records"
    :loading="pageData.loading"
    :pagination="pageData.pagination"
    @pageChange="handlePageChange"
    @rowDbClick="handleRowDbClick"
    :showRefresh="true"
    :showExport="false"
    @refreshData="handleTableRefresh"
  >
    <template #rowOperations="{ row }">
      <div class="crud-table__row_operations">
        <t-link variant="text" theme="primary" @click="handleOperateRow('view', row)">查看</t-link>
        <t-link variant="text" theme="primary" @click="handleOperateRow('edit', row)">修改</t-link>
        <t-link
          variant="text"
          theme="danger"
          @click="handleOperateRow('delete', row)"
          v-if="!RESERVED_USERS.includes(row!.userName)"
          >删除</t-link
        >
      </div>
    </template>
  </CrudTable>
  <EditForm
    v-if="pageData.showEditForm"
    :dialogVisible="pageData.showEditForm"
    :mode="pageData.editFormMode"
    :id="pageData.selectedRowId"
    @close="handleDialogClose"
  />
</template>

<script lang="tsx" setup>
import { ref, computed, reactive, defineAsyncComponent } from "vue";
import { DialogPlugin, MessagePlugin, type TableProps } from "tdesign-vue-next";

import { http } from "@/utils/fetch";
import { getValueBySelectData } from "@/utils/tools";
import type { ICrudTableDataPage, TFilterValue } from "@/types";

import { PAGINATION_VALUE, RESERVED_USERS, STATUS_DATA } from "@/common/constants";

const EditForm = defineAsyncComponent(() => import("./components/EditForm.vue"));

const GET_LIST_PATH = "/user/findAll"; // 查询信息接口
const DELETE_ITEM_PATH = "/user/delete"; // 删除接口

const pageData = reactive({
  loading: false,
  tableData: {} as ICrudTableDataPage,
  selectedRow: {},
  selectedRowId: "",
  selectedRowsEvent: {} as Record<string, any>,
  showEditForm: false,
  editFormMode: "",
  filterValue: {
    id: "",
    userName: "",
    status: null
  } as TFilterValue,
  pagination: {
    pageSize: 20,
    total: 0,
    current: 1
  }
});

// 表格操作按钮配置
const tableButtons = computed(() => [
  {
    name: "新增",
    click: () => {
      pageData.editFormMode = "new";
      pageData.showEditForm = true;
    }
  }
]);

// 表格列配置
const tableColumns = ref<TableProps["columns"]>([
  {
    colKey: "userName",
    title: "用户名",
    width: 150,
    filter: {
      type: "input",
      resetValue: "",
      // 按下 Enter 键时也触发确认搜索
      confirmEvents: ["onEnter"],
      showConfirmAndReset: true
    }
  },
  { colKey: "realName", title: "姓名", width: 150 },
  { colKey: "phone", title: "电话号码", width: 200 },
  {
    colKey: "status",
    title: "用户状态",
    width: 150,
    // 根据 userStatus 显示不同的状态标签
    cell: (h, { row }) => {
      return getValueBySelectData(STATUS_DATA, row.status);
    },
    filter: {
      type: "single",
      list: STATUS_DATA,
      resetValue: "",
      confirmEvents: ["onEnter"],
      showConfirmAndReset: true
    }
  }
]);

// 获取列表数据
const findAllList = async () => {
  pageData.loading = true;
  const resultData = await http(
    "GET",
    `${GET_LIST_PATH}?page=${pageData.pagination.current}&pageSize=${pageData.pagination.pageSize}`
  );
  if (resultData.code === 200) {
    console.dir(resultData.data);
    pageData.tableData = resultData.data;
    pageData.pagination.total = resultData.data.total;
    pageData.pagination.current = resultData.data.current;
    pageData.pagination.pageSize = resultData.data.size;
    pageData.loading = false;
  }
};

const handlePageChange = (pageInfo: Record<string, any>, newDataSource: Record<string, any>) => {
  console.log(pageInfo, newDataSource);
  pageData.pagination.pageSize = pageInfo.pageSize;
  pageData.pagination.current = pageInfo.current;
  findAllList();
};

// 过滤事件触发函数
// const filterChange = (filters: Record<string, any>) => {
//   pageData.filterValue = filters;
//   pageData.pagination = structuredClone(PAGINATION_VALUE);
//   findAllList();
// };

const handleTableRefresh = () => {
  pageData.selectedRow = {};
  pageData.selectedRowId = "";
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  // pageData.filterValue = {};
  findAllList();
};

const handleRowDbClick = (context: Record<string, any>) => {
  handleOperateRow("view", context.row);
};

const handleOperateRow = (mode: string, row?: Record<string, any>) => {
  if (mode !== "delete") {
    if (mode === "new") {
      pageData.selectedRow = {};
      pageData.selectedRowId = "";
    } else {
      pageData.selectedRow = row!;
      pageData.selectedRowId = row!.id;
    }
    pageData.editFormMode = mode;
    pageData.showEditForm = true;
  } else if (mode === "delete") {
    if (RESERVED_USERS.includes(row!.userName)) {
      MessagePlugin.error("不能删除系统保留用户！");
      return;
    }
    const confirmDialog = DialogPlugin({
      header: "警告",
      body: "确定要删除这一条数据吗？",
      confirmBtn: "确定",
      cancelBtn: "取消",
      theme: "warning",
      onConfirm: async () => {
        const deleteData = await http("DELETE", `${DELETE_ITEM_PATH}?id=${row!.id}`);
        if (deleteData.code === 200) {
          MessagePlugin.success("删除成功！");
          findAllList();
          confirmDialog.hide();
        }
      },
      onClose: () => {
        confirmDialog.hide();
      }
    });
  } else {
    MessagePlugin.error("错误：未知的表格操作模式。");
  }
};

const handleSelectChange = (e: Record<string, any>) => {
  pageData.selectedRowsEvent = e;
};

// 对话框关闭时的处理函数
const handleDialogClose = (e: string) => {
  if (e === "success") {
    MessagePlugin.success("操作成功！");
    findAllList();
  }
  pageData.showEditForm = false;
};

// 初始化列表
findAllList();
</script>
